// pages/store/store.js
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        collects: [],
        network: false,
        loading: false,
        page: 1,
        loadingMore: true
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this;
        that.getCollects();
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        var that = this;
        that.setData({
            page: 1,
            collects: [],
        });
        that.getCollects();
        wx.stopPullDownRefresh();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function (e) {
        var that = this;
        /*判断是否有更多数据 */
        if (!that.data.loadingMore) {
            return;
        }
        /*判断是否加载完成*/
        if (that.data.loading) {
            return;
        }
        that.getCollects();
    },

    /**
     * 获取评价
     */
    getCollects: function () {
        var that = this;
        var collects = that.data.collects;
        var page = that.data.page;
        var data = {
            user_id: app.globalData.userInfo.id,
            page: page
        }
        that.setData({
            loading: true
        });
        app.common.apiRequest('api/collect/index', data, function (res) {
            that.setData({
                network: true
            });
            collects = collects.concat(res.data);
            var loadingMore = true;
            if (res.data.length < 10) {
                loadingMore = false;
            }
            that.setData({
                collects: collects,
                loading: false,
                page: ++page,
                loadingMore: loadingMore
            });
        });
    },

    //取消收藏
    cancel: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var data = {
            user_id: app.globalData.userInfo.id,
            activity_id: e.currentTarget.dataset.id
        };
        var collects = that.data.collects;
        app.common.apiRequest('api/collect/collectOrCancel', data, function (res) {
            collects.splice(index, 1);
            that.setData({
                collects: collects
            });
        });
    }
})